Flex端调用Java服务的过程

Categories: Flex; Tagged with: ; @ February 20th, 2009 11:14

1. get Operation

2. set arguments

3. AddResponder, Send();

如下:

	private var op:AbstractOperation;
	public function loadEmployees():void {
		op = AppContext.getRemoteObject().getOperation("loadEmployees");	//获得Operation
		 op.arguments = [id];	//设定参数
		 op.send();
		 var at:AsyncToken = op.send();	//Send
		 at.addResponder(this);	//为本实例增加responder
      }
//使用当前类响应, 则应实现IResponder接口, 要实现两个方法, 如下:
//---------------------Responder-------------------------------
	public function result(responderResult:Object):void {
		var resultEvent:ResultEvent = responderResult as ResultEvent;//转换
		var ac:ArrayCollection = resultEvent.result as ArrayCollection;//获得Result
		log.debug("已读取到 " + this + "的职员列表, 职员数目为: " + ac.length);
	}

	public function fault(data:Object):void {
		throw new Error("远程操作失败");
	}

原先的错误方法:

	private var op:AbstractOperation;
	public function loadEmployees():void {
		op = AppContext.getRemoteObject().getOperation("loadEmployees");	//获得Operation
		 op.arguments = [id];	//设定参数
		 op.addEventListener(ResultEvent.RESULT, onSqlResult,false, 0, true);
		 op.send();
		// var at:AsyncToken = op.send();	//Send
		 //at.addResponder(this);	//为本实例增加responder
      }

	private function onSqlResult(e:ResultEvent):void {
		var ac:ArrayCollection = e.result as ArrayCollection;
		for each(var emp:Employee in ac) {
			emp.department = this;
			employeeAC.addItem(emp);
		}
		log.debug("已读取到 " + this + "的职员列表, 职员数目为: " + ac.length);
		op.removeEventListener(ResultEvent.RESULT, onSqlResult);//更错误的方法是没有remove Listener
	}

这样导致该方法被呼叫时, op都会被监听, 成功后取消监听, 如果不取消监听, 则会出现如下输出信息:
第一次调用:
[DEBUG] Department 已读取到 Dep1的职员列表, 职员数目为: 2

第二次调用:
[DEBUG] Department 已读取到 Dep1的职员列表, 职员数目为: 2
[DEBUG] Department 已读取到 Dep2的职员列表, 职员数目为: 2

第三次调用:
[DEBUG] Department 已读取到 Dep1的职员列表, 职员数目为: 0
[DEBUG] Department 已读取到 Dep2的职员列表, 职员数目为: 0
[DEBUG] Department 已读取到 Department3的职员列表, 职员数目为: 0

在此情况下, op可视为一类操作, 这样在使用op[他会有很多个实例, 会有很多个对应的监听函数]监听之后, 每个实例的Result的返回都会引发所有实例的Listener运行. 因此会出现上面的状况.

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.